<?php



class Am_Form_Admin_Job extends Am_Form_Admin {
    /** @var User */
    protected $record;
	protected $key = "456";
	protected $switch = 0;
	protected $type = 1;
    function __construct($record)
    {
        $this->record = $record;

        parent::__construct('job');
    }
	function checkUrl(array $group)
    {
        $url = $group['url'];
	
        if (!Am_Validate::url($url))
            return  ___('Please enter valid Url');     
    }
	function checkAPIkey()
	{
		$apiNeo = Am_Di::getInstance()->apineo;
		$data = $apiNeo->checkAPIKey();
		if(!$data)
			return ___('API Key not match. Please use another API key.');
		
	}
    function init()
    {
        /* General Settings */
		
        $fieldSet = $this->addElement('fieldset', 'general', array('id'=>'general', 'label' => ___('General')));
		

		$loginGroup = $fieldSet->addGroup('', array('id' => 'url',))->setLabel(___('Url'));
		
		
        $login = $loginGroup->addElement('text', 'url', array('size' => 20));
     	$login->addRule('required');
        $loginGroup->addRule('callback2', '-error-', array($this, 'checkUrl'));
		$url_js = ROOT_URL . '/application/default/views/public/js/scrap.js';
		$url_scrap = ROOT_URL . '/scrap?sw=1';
		$url_keytag = ROOT_URL . '/scrap?sw=2';
		$url_spinurl = ROOT_URL . '/scrap?sw=3';
		
		$loginGroup->addElement('static')
		->setContent(<<<CUT
<div style="margin-top: 10px">
<input type='button' value='1' id='scrap' urlget='$url_scrap' title='Scrape meta tags data from this URL then auto spin and fill to keywords, tags, description fields'/>
<input type='button' value='2' id='keytag' urlget='$url_keytag' title='Scrape Meta Keyword tag data from this URL then auto spin and fill to keywords, tags fields'/>
<input type='button' value='3' id='spinurl' urlget='$url_spinurl' title='Convert Multi URLs separated by commas to spin format'/>
</div>
<script type="text/javascript" src='$url_js'/>
</script>
CUT
);
		
		
		$titleGroup = $fieldSet->addGroup('', array('id' => 'title',))->setLabel(___('Keywords'));
		$title = $titleGroup->addElement('text', "title", null);
		
		$url_genkey = ROOT_URL . '/scrap?sw=4';
		$url_spinkey = ROOT_URL . '/scrap?sw=5';
		$titleGroup->addElement('static')->setContent(<<<CUT
<div style="margin-top: 10px">
<select title="Scrape from list of one character (A,B,C,D,E...) or two character (AA,AB,AC,AD,AE...)" name="character" id="character">
<option value="1">1 Char</option>
</select>
<input type="button" title="Scrape longtail keywords from Google Suggestion" urlget="$url_genkey" id="gen_key" value="4"/>
<input type="hidden" value="" id="temp_keyword">
<input type="button" title="Spin Keywords field from separated by commas to spin format" urlget="$url_spinkey" id="spinkey" value="5"/>
</div>
CUT
);
		$tags =  $fieldSet->addElement('text', "tags", null)->setLabel(___('Tags'));
		$descriptionGroup = $fieldSet->addGroup('', array('id' => 'description',))->setLabel(___('Description'));
		$description = $descriptionGroup->addTextarea("description", array('style'=>"width:90%", 'id' => 'description'));
		
		$url_gendes = ROOT_URL . '/scrap?sw=6';
		$url_testspin = ROOT_URL . '/scrap?sw=7';
		for($i = 1; $i<=15; $i++)
		$option .= "<option value='$i'>$i</option>";
		$descriptionGroup->addElement('static')->setContent(<<<CUT
<div style="margin-top: 10px">
<select title="Number of description to generate" name="des_num" id="des_num">
	$option
													
</select>
                        
<input type="button" title="Auto generate Description from Article Directory" urlget="$url_gendes" id="gen_des" value="6"/>
<input type="button" title="View Example Spin for this Description" id="test_spin" urlget="$url_testspin" value="7"/>
</div>
CUT
);
		
		$c = Am_Di::getInstance()->config;
		$arr_config = $c->getArray();
		$arr_submission = $arr_config['job-submission'];
		$submission = $fieldSet->addSelect('main_success', null, null)->setLabel(___('No. Of Submission'));
		sort($arr_submission);
		foreach($arr_submission as $item)
		{
			if($item == 0)
			$submission->addOption(___("MAX"), $item );		
			else
			$submission->addOption(___("$item"), $item );		
		}
		
		$driplink = $fieldSet->addSelect('bookmark_schedule', null, null)->setLabel(___('No. of Drip Links'));
		for($i = 0 ; $i<=200; $i++)
		{
			if($i == 0)
			$driplink->addOption(___("Don't use"), $i );		
			else
			$driplink->addOption(___("$i"), $i );			
		}
		$driplink_hours = $fieldSet->addSelect('hour_schedule', null, null)->setLabel(___('Drip Links every ___ hours'));
		for($i = 0 ; $i<=720; $i++)
		{
			if($i == 0)
			$driplink_hours->addOption(___("Don't use - Instant"), $i );		
			else
			{
				if($i%24==0)
					$op_temp = $i . " - " . ($i/24) . ' day(s)';	
				else
					$op_temp = $i;
				
				$driplink_hours->addOption(___("$op_temp"), $i );	
			}
						
		}
		
		$auto_vote = $fieldSet->addSelect('vote', null, null)->setLabel(___('Auto Vote - Currently Free'));
		$auto_vote->addOption(___("Don't Vote"), 0 );
		$auto_vote->addOption(___("5-10 (+1 pt)"), 1 );
		$auto_vote->addOption(___("10-15 (+2 pts)"), 2 );
		$auto_vote->addOption(___("15-20 (+3 pts)"), 3 );
	
		$user_id_temp = $fieldSet->addElement('hidden', 'user_id', array('value' => Am_Lite::getInstance()->getUserID()));
		if($this->record->isLoaded())
		$job_id_server = $fieldSet->addElement('hidden', 'job_id_server');
		$decaptcher = $fieldSet->addElement('hidden', 'decaptcher', array("value" => 1));
		$report_email = $fieldSet->addElement('hidden', 'report_email', array("value" => 1));
		
		$email_from = $fieldSet->addElement('hidden', 'email_from', array("value" => $c->get('admin_email')));
		$email_to = $fieldSet->addElement('hidden', 'email_to', array("value" => Am_Lite::getInstance()->getEmail()));
		$client_name = $fieldSet->addElement('hidden', 'client_name', array("value" => Am_Lite::getInstance()->getName()));
		$project_id = $fieldSet->addElement('hidden', 'project_id', array("value" => Am_Di::getInstance()->config->getAPIProject()));
		$list_site_id = $fieldSet->addElement('hidden', 'list_site_id', array("value" => 372));
		$api_temp = $fieldSet->addElement('hidden', 'api_temp');
		$api_temp->addRule('callback2', '-error-', array($this, 'checkAPIKey'));
    	
		
		if ($this->isSubmitted() && $this->validate())
		{
			$data = $this->getValue();
			$apiNeo = Am_Di::getInstance()->apineo;
			
			
			
		
			
			
				$apiNeo->setAPIFull(1, 1);
			
			
				if($this->record->isLoaded())
				{
					
					$data_update = array(
						"id" =>	$data['job_id_server'],
						"url" => isset($data['url']) ? $data['url'] : "",
						"title" => isset($data['title']) ? $data['title'] : "",
						"tags" => isset($data['tags']) ? $data['tags'] : "",
						"description" => isset($data['description']) ? $data['description'] : "",
						"status" => "stop",
						"priority" => $data['priority'],
						"list_site_id" => $data['list_site_id'],
						"main_success" => $data['main_success'],
						"vote"	=> $data['vote'],
						"bookmark_schedule" => $data['bookmark_schedule'],
						"hour_schedule" => $data['hour_schedule'],
						"decaptcher" => $data['decaptcher'],
						"report_email" => $data['report_email'],
						"email_from" => $data["email_from"],
						"email_to" => $data["email_to"],
						"client_name" => $data["client_name"],
						"project_id" => $data['project_id'],
						"list_site_id" => $data['list_site_id']
					);
					$result =	$apiNeo->updateAPIData($data_update);
					
					
				}	
				else
				{
					
					
					$data_insert = array(
					
						"url" => isset($data['url']) ? $data['url'] : "",
						"title" => isset($data['title']) ? $data['title'] : "",
						"tags" => isset($data['tags']) ? $data['tags'] : "",
						"description" => isset($data['description']) ? $data['description'] : "",
						"status" => "stop",
						"priority" => $data['priority'],
						"list_site_id" => $data['list_site_id'],
						"main_success" => $data['main_success'],
						"vote"	=> $data['vote'],
						"bookmark_schedule" => $data['bookmark_schedule'],
						"hour_schedule" => $data['hour_schedule'],
						"decaptcher" => $data['decaptcher'],
						"report_email" => $data['report_email'],
						"email_from" => $data["email_from"],
						"email_to" => $data["email_to"],
						"client_name" => $data["client_name"],
						"project_id" => $data['project_id'],
						"list_site_id" => $data['list_site_id']
					);	
					$result = $apiNeo->insertAPIData($data_insert);
				
					$job_id_server = $fieldSet->addElement('hidden', 'job_id_server');
					$job_id_server->setValue($result);		
				}					
				
			
			
			
		}
	
	}
	
	
}
class Am_Grid_Filter_Job extends Am_Grid_Filter_Abstract
{
    protected $title;
    public function __construct()
    {
        $this->title = ___("Filter By Url");
        parent::__construct();
    }
    public function getVariablesList()
    {
        $ret = parent::getVariablesList();
        $ret[] = 'search';
        $ret[] = 'search_load';
        return $ret;
    }
    protected function applyFilter()
    {
        // done in initFilter
    }
  
   
    public function renderInputs()
    {
        return $this->renderInputText('filter');
    }
    public function initFilter(Am_Grid_ReadOnly $grid)
    {
        parent::initFilter($grid);
        $query = $grid->getDataSource();
       // $query->setPrefix('_u_search');
        /* @var $query Am_Query_User */
        if ($id = $grid->getRequest()->getInt('search_load')){
            $query->load($id);
        } elseif (is_string($this->vars['filter']) && $this->vars['filter']){
            $cond = new Am_Query_Job_Condition_Filter();
			
            $cond->setFromRequest(array('filter' => array('val' => $this->vars['filter'])));
            $query->add($cond);
        } else {
            $query->setFromRequest($grid->getCompleteRequest());
        }
    }
    public function isFiltered()
    {
        return (bool)$this->grid->getDataSource()->getConditions();
    }
}

class UsercpJobsController extends Am_Controller_GridUsercp
{
    public function preDispatch()
    {
        parent::preDispatch();
		$this->getDi()->auth->requireLogin(ROOT_URL . '/member');
        $this->setActiveMenu($this->getParam('_j_a')=='insert' ? 'jobs-insert' : 'jobs-browse');
    }
    
 
    
    public function createGrid()
    {
       	//$ds = new Am_Query($this->getDi()->jobTable);
		$ds = new Am_Query_Job;
		$ds->addField('(SELECT count(a.id) FROM ?_auto_vote a WHERE a.job_id_server = j.job_id_server)',  'reports_count');
		$ds->addWhere("`user_id` = ?", Am_Lite::getInstance()->getUserID());
		$ds->setOrder('job_id_server');
      //  $ds->setOrderRaw("0+IFNULL(sort_order,0),title");
      /*  $ds->addField("concat(name_f, ' ', name_l)", 'name')
          ->addField('(SELECT count(p.invoice_payment_id) FROM ?_invoice_payment p WHERE p.user_id = u.user_id)',  'payments_count')
          ->addField('IFNULL((SELECT sum(p.amount) FROM ?_invoice_payment p WHERE p.user_id = u.user_id),0)-' .
                     'IFNULL((SELECT sum(r.amount) FROM ?_invoice_refund r WHERE u.user_id=r.user_id),0)',  
              'payments_sum');*/
        //$ds->setOrder("login");
        $grid = new Am_Grid_Editable('_j', ___("Browse Jobs"), $ds, $this->_request, $this->view);
		$grid->setRecordTitle(___('Job'));
		$grid->addGridField(new Am_Grid_Field('job_id', 'ID', true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('job_id_server', ___('IDServer'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('user_id', ___('User ID'), true, '', null, '5%'));
		
		$grid->addGridField(new Am_Grid_Field('url', ___('Url'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('title', ___('Title'), true, '', null, '5%'));
		
		$grid->addGridField(new Am_Grid_Field('tags', ___('Tags'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('description', ___('Description'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('decaptcher', ___('Decaptcher'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('priority', ___('Priority'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('vote', ___('Vote'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('main_success', ___('Main success'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('submitted', ___('Submitted'), true, '', null, '5%'));
		$grid->addGridField(new Am_Grid_Field('list_site_id', ___('Site ID'), true, '', null, '5%'));
		
		$grid->setForm(array($this, 'createForm'));
		 $grid->actionGet('insert')->setTarget('_top')->showFormAfterSave(true);
		$grid->actionAdd($this->createActionExport());
		
		$grid->actionAdd($this->createActionCustomize());	
		
		$actDelInLine = new Am_Grid_Action_Delete();
		$actDelInLine->setJob(true);
		$actDelInLine->setAPI(1, 1);
		$grid->actionAdd($actDelInLine);
		$actDel = new Am_Grid_Action_Group_Delete();
		$actDel->setJob(true);
		$actDel->setAPI(1, 1);
		$grid->actionAdd($actDel);
		
		
		$actTest = new Am_Grid_Action_Url('reports', ___('View Report this Job'), '__ROOT__/usercpjobsreport?jobid=__ID__', '_dreport');
		
		
		
		$grid->actionAdd($actTest);
		
		$actDownload = new Am_Grid_Action_Url('download', ___('Download Report this Job'), '__ROOT__/download?jobid=__ID__', '_dreport');
	
		$grid->actionAdd($actDownload);
	//	$grid->actionAdd(new Am_Grid_Action_DownloadReport());
		$grid->setFilter(new Am_Grid_Filter_Job());
		
    	/* $grid->addField(new Am_Grid_Field('name', ___('Name'), true));
		  $grid->addField(new Am_Grid_Field('email', ___('E-Mail Address'), true));
		   $grid->addField(new Am_Grid_Field('payments_sum', ___('Payments'), true, null, null));*/
        return $grid;
    }
	function createForm()
    {
        return new Am_Form_Admin_Job($this->grid->getRecord());
    }
	protected function createActionCustomize() {
        $action = new Am_Grid_Action_Customize();
		$action->setUser(true);
        $action->addField(new Am_Grid_Field('job_id', ___('Job Id')))
			->addField(new Am_Grid_Field('job_id_server', ___('Job Id Server')))
			->addField(new Am_Grid_Field('user_id', ___('User_Id')))
            ->addField(new Am_Grid_Field('url', ___('Url')))
			->addField(new Am_Grid_Field('title', ___('Title')))
            ->addField(new Am_Grid_Field('tags', ___('Tags')))
			->addField(new Am_Grid_Field('reports_count', ___('Reports')))
			->addField(new Am_Grid_Field('description', ___('Description')))
			->addField(new Am_Grid_Field('decaptcher', ___('Decaptcher')))
			->addField(new Am_Grid_Field('priority', ___('Priority')))
			->addField(new Am_Grid_Field('main_success', ___('Main success')))
			->addField(new Am_Grid_Field('submitted', ___('Submitted')))
			->addField(new Am_Grid_Field('list_site_id', ___('Site ID')))
			->addField(new Am_Grid_Field('vote', ___('Vote')));
          
			
        
            //Additional Fields
        foreach ($this->getDi()->jobTable->customFields()->getAll() as $field) {
            if (isset($field->from_config) && $field->from_config) {
                if ($field->sql) {
                    $action->addField(new Am_Grid_Field($field->name, $field->title));
                } else {
                    $action->addField(new Am_Grid_Field_Data($field->name, $field->title));
                }
            }
        }

        return $action;
    }
	 protected function createActionExport() {
        $action = new Am_Grid_Action_Export();
		$action->setJobId(0);
		$action->setUser(true);
        $action->addField(new Am_Grid_Field('job_id', ___('Job Id')))
		 	->addField(new Am_Grid_Field('job_id_server', ___('Job Id Server')))
			->addField(new Am_Grid_Field('user_id', ___('User_Id')))
            ->addField(new Am_Grid_Field('url', ___('Url')))
			->addField(new Am_Grid_Field('title', ___('Title')))
            ->addField(new Am_Grid_Field('tags', ___('Tags')))
			->addField(new Am_Grid_Field('description', ___('Description')));
        
        //Additional Fields
        foreach ($this->getDi()->jobTable->customFields()->getAll() as $field) {
            if (isset($field->from_config) && $field->from_config) {
                if ($field->sql) {
                    $action->addField(new Am_Grid_Field($field->name, $field->title));
                } else {
                    //we use trailing __ to distinguish fields from data table
                    $action->addField(new Am_Grid_Field($field->name . '__', $field->title));
                }
            }
        }
        
      //  $action->setGetDataSourceFunc(array($this, 'getDS'));
        return $action;
    }
	
	

   
}
